

from flask import render_template, request, jsonify, current_app, session, redirect, url_for, g
import logging

from info import constants
from info.lib.Decorator.Decorator_init import user_login
from info.models import User
from info.utlis.response_code import RET
from . import admin_blu
import time

@admin_blu.route("/login", methods=['POST','GET'])
@user_login
def login():

    user = g.user

    if request.method == 'GET':
        # 如果管理员已经登陆，则直接跳过登陆界面，
        if user:
            if not user.is_admin:
                return redirect(url_for('/'))

        return render_template('admin/login.html')
    # 如果提交数据
    if request.method == 'POST':

        # 获取参数
        username = request.form.get('username')
        password = request.form.get('password')

        # 判断是否为空
        if not all([username,password]):
            return render_template('admin/login.html',errmsg='用户名或密码不可为空')

        # 查询数据库，校验用户名
        try:
            admin_user = User.query.filter(User.mobile == username).first()
        except Exception as e:
            current_app.logger.debug(e)
            return render_template('admin/login.html',errmsg='数据库查询错误')

        # 校验用户名
        if not admin_user:
            return render_template('admin/login.html',errmsg='用户名不存在')

        # 校验密码是否正确
        if not admin_user.check_password(password):
            return render_template('admin/login.html',errmsg='密码错误')

        if admin_user.is_admin != 1:
            return render_template('admin/login.html', errmsg='用户权限不够')

        # 登陆状态保持
        session['is_admin'] = True
        session['user_id'] = admin_user.id
        session['mobile'] = admin_user.mobile
        session['nick_name'] = admin_user.nick_name


        return redirect(url_for('admin.index'))

@admin_blu.route('/index',methods=['POST','GET'])
@user_login
def index():
    """
    1 返回日新增数和月新增数和总数的值
    2 localtime 本地时间（tm_year,tm_mon,tm_day）
    :return:
    """
    user = g.user

    # 判断用户是否已经登陆
    if not user:
        return redirect('/')

    return render_template('admin/index.html',data={})

@admin_blu.route('/user_count')
@user_login
def user_count():


    user = g.user

    # 创建参数
    total_count = 0  # 总数
    mon_count = 0  # 月新增数
    day_count = 0  # 日新增数

    # 新增总数
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 月新增数
    t = time.localtime()
    from datetime import datetime
    mon_time = datetime.strptime(('%s-%02d-01' % (t.tm_year, t.tm_mon)), '%Y-%m-%d')
    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_time).count()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 日新增数
    day_time = datetime.strptime(('%s-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)), '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_time).count()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    data = {
        'total_count': total_count,
        'mon_count': mon_count,
        'day_count': day_count
    }

    return render_template('admin/user_count.html',data=data)

@admin_blu.route('/user_list',methods=['GET'])
@user_login
def user_list():
    """
    1 取道分页页数
       1
    2 分页展示用户列表
    :return:
    """

    # 获取分页数据
    p = request.args.get('p', 1)
    # 判断参数是否合理
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.REQERR, errmsg='非法请求')

    # 取到所有的分页数据
    try:
        painates = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).painate(p, constants.ADMIN_USER_PAGE_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    #获取总页数
    total_page = painates.pages

    #获取当前页数
    current_page = painates.page

    user_list = []

    for painate in painates:
        user_list.append(painate.to_admin_dict())


    data = {
        "total_page": total_page, # 总页数
        "current_page": current_page, # 当前页数据
        "users": user_list
    }
    return render_template('admin/user_list.html', data=data)